package cn.wolfcode.wolf2w.business.service;

import cn.wolfcode.wolf2w.business.config.DeepSeekProperties;
import cn.wolfcode.wolf2w.business.config.RestTemplateConfig;
import cn.wolfcode.wolf2w.business.domain.Note;
import cn.wolfcode.wolf2w.business.domain.Strategy;
import cn.wolfcode.wolf2w.business.dto.OpenAIChatRequest;
import cn.wolfcode.wolf2w.business.dto.OpenAIChatResponse;
import cn.wolfcode.wolf2w.business.dto.OpenAIMessage;
import com.alibaba.fastjson2.JSON;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@Service
public class DeepseekServiceImpl {
    @Autowired
    private DeepSeekProperties deepSeekProperties;
    @Autowired
    private RestTemplate restTemplate;
    
    /**
     * 调用DeepSeek AI模型获取回答结果
     * 
     * @param question 用户提出的问题
     * @param strategies 从私有知识库中查询到的攻略数据
     * @return AI模型的回答内容
     */
    public String askWithStrategy(String question, List<Strategy> strategies) {
        // 构建系统提示词
        String systemPrompt = buildSystemPrompt(strategies);
        // 创建系统角色消息
        OpenAIMessage system = new OpenAIMessage("system", systemPrompt);
        // 创建用户角色消息
        OpenAIMessage user = new OpenAIMessage("user", question);
        // 构建消息列表
        List<OpenAIMessage> messages = new ArrayList<>();
        messages.add(system);
        messages.add(user);
        // 创建AI聊天请求对象
        OpenAIChatRequest openAIChatRequest = new OpenAIChatRequest();
        openAIChatRequest.setMessages(messages);
        // 设置模型名称
        openAIChatRequest.setModel(deepSeekProperties.getModel());
        // 设置温度参数，控制输出的随机性
        openAIChatRequest.setTemperature(0.3);
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 设置认证信息
        headers.setBearerAuth(deepSeekProperties.getApiKey());

        // 构建HTTP请求实体
        HttpEntity<OpenAIChatRequest> httpEntity = new HttpEntity<>(openAIChatRequest, headers);
        // 构建请求URL
        String url = deepSeekProperties.getBaseUrl() + "/chat/completions";
        // 发送POST请求并获取响应
        OpenAIChatResponse response = restTemplate.postForObject(url, httpEntity, OpenAIChatResponse.class);
        // 检查响应是否有效
        if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
            return "AI没有找到答案";
        }
        // 获取第一个选择项
        OpenAIChatResponse.Choice choice = response.getChoices().get(0);
        // 检查选择项是否有效
        if (choice == null || choice.getMessage() == null) {
            return "AI没有找到答案";
        }
        // 返回AI的回答内容
        return choice.getMessage().getContent();
    }

    /**
     * 构建系统提示词，将攻略数据整合为AI模型的上下文信息
     * 
     * @param strategies 攻略数据列表
     * @return 构建好的系统提示词
     */
    private String buildSystemPrompt(List<Strategy> strategies) {
        // 创建字符串连接器，使用双换行符分隔不同部分
        StringJoiner joiner = new StringJoiner("\n\n");
        // 添加系统角色提示词
        joiner.add("你是一名知名的导游，请基于以下提供的私有知识库数据片段进行分析整理形成一篇只能旅游旅行推荐攻略，不要编造数据。，若资料不足请明确说明\n\n" +
                "以下是来自私有知识库的片段（JSON）");
        // 遍历攻略数据并添加到提示词中
        for (Strategy strategy : strategies) {
            // 将攻略对象转换为JSON字符串
            String jsonString = JSON.toJSONString(strategy);
            joiner.add(jsonString);
        }
        // 返回构建好的系统提示词
        return joiner.toString();
    }
}